package com.woniuxy.hospital.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.hospital.entity.HplAdmin;
import com.woniuxy.hospital.service.IHplAdminService;
import com.woniuxy.hospital.service.IHplPermService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
@Slf4j
public class DbRealm extends AuthorizingRealm {
    @Autowired
    private IHplAdminService adminService;
    @Autowired
    private Audience audience;
    /**
     * 用户的权限
     * @param principalCollection
     * @return info
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Object primaryPrincipal = principalCollection.getPrimaryPrincipal();//获取username
        log.debug("DbRealm----doGetAuthorizationInfo:"+primaryPrincipal.toString());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        int id=0;
        if (primaryPrincipal instanceof String){
            String jwt = primaryPrincipal.toString();
            id = JwtUtil.getId(jwt,audience.getBase64Secret());//获得管理员ID
        }else if(primaryPrincipal instanceof HplAdmin){
            HplAdmin admin =(HplAdmin) primaryPrincipal;
            id = admin.getId();
        }

        //根据用户ID查权限
        adminService.getPermsByAdminId(id).forEach(p->{
            info.addStringPermission(p.getSign());//添加用户权限
        });


        return info;
    }

    /**
     * 用于登录
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token =(UsernamePasswordToken) authenticationToken;
        QueryWrapper<HplAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",token.getUsername());
        //查询用户是否存在
        HplAdmin admin = adminService.getOne(queryWrapper);
        if(admin==null){
            throw new UnknownAccountException("账号：" + token.getUsername() + "不存在");
        }
        //加入作用域中
        SecurityUtils.getSubject().getSession().setAttribute("admin",admin);
        //ByteSource salt = ByteSource.Util.bytes(token.getUsername());//延值加密
        //return new SimpleAuthenticationInfo(admin,admin.getPassword(),salt,getName());

        return new SimpleAuthenticationInfo(admin,admin.getPassword(),getName());

    }
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }
}
